#coding:utf-8

from learn import models

from jira import JIRA
from jenkins import Jenkins
import time, threading



class AutoDeploy:

    jira = None;
    dockerJenkins = None;
    virtualJenkins = None

    def __init__(self, usename, password):
        self.username = usename
        self.password = password

    def isDockerSite(self, siteName):
        siteLists = ['trade.sqseller.ymatou.com',
                     'shenqisettlement.iapi.ymatou.com',
                     'shenqiriskcontrol.iapi.ymatou.com',
                     'sellerquery2.trading.iapi.ymatou.com',
                     'outerpromotion.iapi.ymatou.com',
                     'sqidcard.iapi.ymatou.com',
                     'sellertrade.iapi.ymatou.com',
                     'outerpromotion.iapi.ymatou.com',
                     'tradesafe.iapi.ymatou.com',
                     'sq.admin.ymatou.cn',
                     'sqes.trading.iapi.shop2cn.com',
                     'proxyorder.iapi.ymatou.com',
                     'sqsellerquery.iapi.shop2cn.com',
                     'squserquerytrade.iapi.shop2cn.com']

        if siteName in siteLists:
            return True;

    # 登录Jira
    def loginJira(self):
        AutoDeploy.jira = JIRA('http://jira.ymatou.cn:8080/', basic_auth = (self.username, self.password));

    #主单操作
    def operateMainIssue(self, jiraNumber):
        # 获取主单号

        mainIssue = models.MainIssue;

        mainIssue.jiraMainIssue = AutoDeploy.jira.issue(jiraNumber)

        status = mainIssue.fields.status
        assignee = mainIssue.fields.assignee

        print(status)
        print(assignee)

        #如果主单流程为‘子任务激活’，则主单流程测试人员已经结束
        if str(status) == '子任务激活':
            return mainIssue;
        else:
            # 设置经办人
            if assignee is None:

                issue_dict= {'assignee':{'name': 'cszhangyi'}}
                mainIssue.errorMsg = '没有设置经办人，请手动设置经办人'

            elif str(assignee) != '张翼':
                # 更新assignee
                mainIssue.jiraMainIssue.update(assignee = {'name':'cszhangyi'})

            # 更新流程
            subTransitions = AutoDeploy.jira.transitions(mainIssue.jiraMainIssue)

            if len(subTransitions) == 0:
                mainIssue.errorMsg = '主单提测，请开发人员提测'
            elif subTransitions[0]['id'] == '41':
                #主单SIT测试通过
                AutoDeploy.jira.transition_issue(mainIssue.jiraMainIssue, '41')
                time.sleep(3)
                #主单UAT测试通过
                AutoDeploy.jira.transition_issue(mainIssue.jiraMainIssue, '71')
            elif subTransitions[0]['id'] == '71':
                #主单UAT测试通过
                AutoDeploy.jira.transition_issue(mainIssue.jiraMainIssue, '71')
            else:
                mainIssue.errorMsg = '没有可操作的工作流'

        return mainIssue

    #子单操作
    def getSubTasks(self, mainJiraIssue, isRetry, isStgSuccess, branch = 'master', gitVersion = ''):
        # 获取jira单下的子任务
        subtasks = mainJiraIssue.fields.subtasks
        jenkins = None

        threads = []

        # 如果jira单有子任务
        if len(subtasks) > 0:

            for subtask in subtasks:

                subIssue = AutoDeploy.jira.issue(str(subtask))
                AutoDeploy.operateSubTasks(self, subIssue, isRetry, isStgSuccess, branch, gitVersion, threads)
        else:
            AutoDeploy.operateSubTasks(self, mainJiraIssue, isRetry, isStgSuccess, branch, gitVersion, threads)

        for t in threads:
            t.setDaemon(True)
            t.start()

        for t in threads:
            t.join()

    #子单操作
    def operateSubTasks(self, subIssue, isRetry, isStgSuccess, branch = 'master', gitVersion = '', threads = []):

        subIssueStatus = subIssue.fields.status
        print(subIssueStatus)
        subTransitions = AutoDeploy.jira.transitions(subIssue)

        job_name = str(subIssue.fields.customfield_12903[0])

        if str(subIssueStatus) ==  "新建" or str(subIssueStatus) == "STAGE测试" or str(subIssueStatus) == "生产测试" or str(subIssueStatus) == "研发Leader确认STAGE发布":

            if str(subIssueStatus) == "新建" or str(subIssueStatus) == "研发Leader确认STAGE发布":

                if gitVersion == '':
                    if isRetry:
                        print(job_name + ' 再次发布STG，去jenkins发布版本，重新获取版本号，并发布STG')

                    else:
                        print(job_name + ' 首次发布STG，去jenkins发布版本，获取版本号，并发布STG')

                    if AutoDeploy.isDockerSite(self, job_name):
                        t = threading.Thread(target = AutoDeploy.updateGitVersion, args = (self, self.dockerJenkins, job_name, subIssue, branch))
                    else:
                        t = threading.Thread(target = AutoDeploy.updateGitVersion, args = (self, self.virtualJenkins, job_name, subIssue, branch))

                    threads.append(t)
                else:
                    #更新版本号
                    subIssue.update(customfield_12800 = gitVersion)
                    #确认STG发布
                    AutoDeploy.jira.transition_issue(subIssue, '501')

            elif str(subIssueStatus) == "STAGE测试":
                #如果版本号正确，STG测试成功，如果版本号不正确，则重新发布STG
                if isStgSuccess:
                    print(job_name + ' 测试完成，发布上线')
                    AutoDeploy.jira.transition_issue(subIssue, '371')
                else:

                    if gitVersion == '':
                        print(job_name + ' 重新发布STG，去jenkins发布版本，获取版本号，并重新发布STG')
                        if AutoDeploy.isDockerSite(self, job_name):
                            t = threading.Thread(target = AutoDeploy.updateGitVersion, args = (self, self.dockerJenkins, job_name, subIssue, branch))
                        else:
                            t = threading.Thread(target = AutoDeploy.updateGitVersion, args = (self, self.virtualJenkins, job_name, subIssue, branch))
                        threads.append(t)
                    else:
                        subIssue.update(customfield_12800 = gitVersion)
                        AutoDeploy.jira.transition_issue(subIssue, '401')
        else:
            print(str(subIssue) + "等待研发人员操作")

    # 登录jenkins
    def loginVirtualJenkins(self):
        AutoDeploy.virtualJenkins = Jenkins(url = "http://172.16.100.44:8080/", username = self.username, password = self.password)

    def loginDockerJenkins(self):
        AutoDeploy.dockerJenkins = Jenkins(url = "http://dockerci.better.ymatou.com/", username = self.username, password = self.password)

    def buildJob(self, jenkins, job_name, branch):
        if AutoDeploy.isDockerSite(self, job_name):
            jenkins.build_job(job_name, {'ENV': 'SIT1', 'BRANCH': branch})
        else:
            jenkins.build_job(job_name, {'env': 'SIT1', 'branch': branch})

    def getQueueInfo(self, jenkins, job_name):
        queue_info = jenkins.get_queue_info()

        if queue_info:
            for queue_job_info in queue_info:
                if queue_job_info['task']['name'] == job_name:
                    print(job_name + ' 挂起,排队构建中')
                    time.sleep(10)
                    AutoDeploy.getQueueInfo(self, jenkins, job_name)

    def getJobBuildState(self, jenkins, job_name, n = 0):
        AutoDeploy.getQueueInfo(self, jenkins, job_name)

        if n == 0:
            print(job_name + ' 开始构建')

        #获取job的最后次构建号
        lastbuildNumber = jenkins.get_job_info(job_name)['lastBuild']['number']
        build_state = jenkins.get_build_info(job_name, lastbuildNumber)['result']

        #print(build_state, type(build_state))

        if build_state == 'SUCCESS':
            print(job_name + ' 构建成功')
        elif build_state == 'FAILURE':
            print(job_name + '构建失败')
            lastbuildNumber = 0
        elif build_state is None:
            time.sleep(10)
            AutoDeploy.getJobBuildState(self, jenkins, job_name, 1)

        return lastbuildNumber

    def getGitVersion(self, jenkins, job_name, number):

        strBuildConsoleOutput = str(jenkins.get_build_console_output(name = job_name, number = number))
        index = strBuildConsoleOutput.find('版本 ：')
        gitVersion = strBuildConsoleOutput[index + 4 : index + 12]

        if (gitVersion.startswith('G') or gitVersion.startswith('T')) == 0:
            print('发布失败')
            return;

        print(gitVersion)

        return gitVersion

    def updateGitVersion(self, jenkins, job_name, subIssue, branch):
        AutoDeploy.buildJob(self, jenkins, job_name, branch)
        lastbuildNumber = AutoDeploy.getJobBuildState(self, jenkins, job_name)

        if lastbuildNumber != 0:
            gitVersion = AutoDeploy.getGitVersion(self, jenkins, job_name, lastbuildNumber)

            #更新版本号
            subIssue.update(customfield_12800 = gitVersion)

            print(job_name + ' 更新版本号')
            subIssueStatus = subIssue.fields.status

            str(subIssueStatus) == "STAGE测试"

            if str(subIssueStatus) == "研发Leader确认STAGE发布":
                print(job_name + ' 更新版本号')
            else:
                #确认STG发布
                self.jira.transition_issue(subIssue, '501')
                print(job_name + ' 发布STG')